package com.laixu.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyProxyFactory {

    @SuppressWarnings("unchecked")
    public static <T> T getProxy(T target) {
        // 获取目标类的类加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        // 获取目标类实现的接口列表
        Class<?>[] interfaces = target.getClass().getInterfaces();
        // 创建 InvocationHandler 实现类
        InvocationHandler handler = new MyInvocationHandler(target);

        // 动态生成代理对象
        T proxy = (T) Proxy.newProxyInstance(
                classLoader,
                interfaces,
                handler
        );

        return proxy;
    }

    // 内部类实现 InvocationHandler
    private static class MyInvocationHandler implements InvocationHandler {
        private final Object target;

        public MyInvocationHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // 日志记录：输出类名和方法名
            String className = target.getClass().getName();
            String methodName = method.getName();
            System.out.println(className + " 类型对象中的 " + methodName + " 方法被调用了");

            // 反射调用目标方法
            Object result = method.invoke(target, args);
            return result;
        }
    }
}